// pages/login/login.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isHide: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData)
    var that = this;
    //判断是否授权
    wx.getSetting({
      success: res => {
        console.log(res);
        if(res.authSetting['scope.userInfo']){
          //已经授权
          wx.cloud.callFunction({
            name: 'login',
            data: {},
            success: res => {
              console.log('[云函数] [login] user openid: ', res.result.openid)
              app.globalData.openid = res.result.openid
              
            },
            fail: err => {
              console.error('[云函数] [login] 调用失败', err)
              
            }
          })
          wx.getUserInfo({
            success: res => {
              console.log(res)
              
              app.globalData.nickName = res.userInfo.nickName;
              app.globalData.avatarUrl = res.userInfo.avatarUrl;
            }
          })
          wx.switchTab({
            url: '../home/home',
          })
        } else{
          that.setData({
            isHide: true
          })
        }
      }
    })
  },

  bindGetUserInfo: function (e) {
    console.log(e)

    if(e.detail.userInfo){
      //用户信息获取成功
      wx.cloud.callFunction({
        name: 'login',
        data: {},
        success: res => {
          console.log('[云函数] [login] user openid: ', res.result.openid)
          app.globalData.openid = res.result.openid

        },
        fail: err => {
          console.error('[云函数] [login] 调用失败', err)
        }
      })
      app.globalData.nickName = e.detail.userInfo.nickName;
      app.globalData.avatarUrl = e.detail.userInfo.avatarUrl;
      wx.switchTab({
        url: '../home/home',
      })
    }else{
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权 ，将无法进入小程序，请授权后再进入',
        showCancel: false,
        confirmText: '返回授权',
        
      })
    }
  }
})